package jms.mq;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Logger;

/**
 * 消息处理中心服务
 */
public class BrokerServer implements Runnable {
    private static final Logger logger = Logger.getGlobal();

    public static int SERVER_PORT = 9999;
    private final Socket socket;

    public BrokerServer(Socket socket) {
        this.socket = socket;
    }


    @Override
    public void run() {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            PrintWriter out = new PrintWriter(socket.getOutputStream());

            while (true) {
                String str = in.readLine();
                if (str == null) {
                    continue;
                }

                logger.info(String.format("接受的原始数据: %s", str));

                if (str.contains("CONSUME")) {
                    // CONSUMER 表示要消费一条消息
                    // 从消息队列中消费一条消息
                    String message = Broker.consume();
                    out.println(message);
                    out.flush();
                } else if (str.contains("SEND")) {
                    // 接受请求包含 SENE, 表示生产消息放到消息队列中
                    Broker.produce(str);
                } else {
                    logger.info(String.format("原始数据: %s; 没有遵循协议, 不提供相关服务", str));
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public static void main(String[] args) throws IOException {
        ServerSocket socket = new ServerSocket(SERVER_PORT);

        logger.info("MQ server starting ...");

        while (true) {
            BrokerServer brokerServer = new BrokerServer( socket.accept() );
            new Thread(brokerServer).start();
        }
    }
}
